package cn.com.thinker.security.sdk.config;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.io.File;

/**
 * Created by crazyHC on 2017/6/29.
 */
@Configuration
@ConditionalOnExpression("${thinker.security.server.port:-1}>0")
public class TomcatConfig {

    @Autowired
    private Environment environment;

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {

        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

            @Override
            protected void postProcessContext(Context context) {

                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    // 支持http，https
    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setSecure(true);
        connector.setPort(environment.getProperty("thinker.security.server.port", Integer.class, 8080));
        Boolean redirectHttps = environment.getProperty("thinker.security.server.redirect-https.enabled", Boolean.class, false);
        // 将HTTP请求重定向到HTTPS
        if(redirectHttps){
            connector.setSecure(false);
            connector.setRedirectPort(environment.getProperty("server.port", Integer.class, 8443));
        }
        return connector;
    }


}
